package com.kinggm.util;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

@Service("simpleRedisLock")
public class SimpleRedisLock implements RedisLock {

    private final String KEY_PREFIX = "REDIS_LOCK_";


    @Override
    public boolean tryLock(StringRedisTemplate stringRedisTemplate, String redisKey, String uuid, long timeoutSec) {
        Boolean result = stringRedisTemplate.opsForValue()
                .setIfAbsent(KEY_PREFIX + redisKey, uuid, timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(result);
    }




    @Override
    public void releaseLock(StringRedisTemplate stringRedisTemplate, String redisKey, String uuid) {
        // 定义lua表达式  实现判断锁标识和释放锁操作的原子性
        String scriptStr = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        DefaultRedisScript<Long> script = new DefaultRedisScript<>();
        script.setScriptText(scriptStr);
        script.setResultType(Long.class);
        stringRedisTemplate.execute(script, Collections.singletonList(KEY_PREFIX + redisKey), uuid);
    }



    @Override
    public void releaseLock(StringRedisTemplate stringRedisTemplate, String redisKey, String uuid, long timeoutSec) {

    }

}
